package com.alibaba.nacos.core.listener;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class DESUtils {
	/* 加密算法,可用 DES DESede Blowfish */
	private final static String ALGORITHM = "DES";

	private static final String SEC_KEY = "nacos@ccb95533";

	private static final Charset CHARSET_UTF8 = StandardCharsets.UTF_8;

	// 对字符串加密
	public final static String encode(String data) {
		return encode(data, SEC_KEY);
	}

	public final static String encode(String data, String key) {
		return byte2hex(encrypt(data, key));
	}

	public final static String decode(String data) {
		return decode(data, SEC_KEY);
	}

	public final static String decode(String data, String key) {
		return new String(decrypt(data, key));
	}

	/**
	 * 用指定的key对数据进行DES加密.
	 *
	 * @param data
	 *            待加密的数据
	 * @param key
	 *            DES加密的key
	 * @return 返回DES加密后的数据
	 * @throws Exception
	 */
	private static byte[] encrypt(String data, String key) {
		try {
			// DES算法要求有一个可信任的随机数源
			SecureRandom sr = new SecureRandom();
			// 从原始密匙数据创建DESKeySpec对象
			DESKeySpec dks = new DESKeySpec(key.getBytes(CHARSET_UTF8));
			// 创建一个密匙工厂，然后用它把DESKeySpec转换成
			// 一个SecretKey对象
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
			SecretKey securekey = keyFactory.generateSecret(dks);
			// Cipher对象实际完成加密操作
			Cipher cipher = Cipher.getInstance(ALGORITHM);
			// 用密匙初始化Cipher对象
			cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
			// 现在，获取数据并加密
			// 正式执行加密操作
			return cipher.doFinal(data.getBytes(CHARSET_UTF8));
		} catch (InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
			throw new RuntimeException("加密失败", e);
		}
	}

	/** */
	/**
	 * 用指定的key对数据进行DES解密.
	 *
	 * @param data
	 *            待解密的数据
	 * @param key
	 *            DES解密的key
	 * @return 返回DES解密后的数据
	 * @throws Exception
	 */
	private static byte[] decrypt(String data, String key) {
		try {
			// DES算法要求有一个可信任的随机数源
			SecureRandom sr = new SecureRandom();
			// 从原始密匙数据创建一个DESKeySpec对象
			DESKeySpec dks = new DESKeySpec(key.getBytes(CHARSET_UTF8));
			// 创建一个密匙工厂，然后用它把DESKeySpec对象转换成
			// 一个SecretKey对象
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
			SecretKey securekey = keyFactory.generateSecret(dks);
			// Cipher对象实际完成解密操作
			Cipher cipher = Cipher.getInstance(ALGORITHM);
			// 用密匙初始化Cipher对象
			cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
			// 现在，获取数据并解密
			// 正式执行解密操作
			return cipher.doFinal(hex2byte(data));
		} catch (InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
			throw new RuntimeException("解密失败", e);
		}
	}

	public static byte[] hex2byte(String b1) {
		byte[] b = b1.getBytes(CHARSET_UTF8);
		if ((b.length % 2) != 0)
			throw new IllegalArgumentException("长度不是偶数");
		byte[] b2 = new byte[b.length / 2];
		for (int n = 0; n < b.length; n += 2) {
			String item = new String(b, n, 2);
			b2[n / 2] = (byte) Integer.parseInt(item, 16);
		}
		return b2;
	}

	public static String byte2hex(byte[] b) {
		int len = b.length;
		StringBuffer sb = new StringBuffer(len);
		String stmp = "";
		for (int n = 0; n < len; n++) {
			stmp = Integer.toHexString(b[n] & 0xFF);
			if (stmp.length() == 1) {
				sb = sb.append("0");
			}
			sb = sb.append(stmp);
		}
		return sb.toString();
	}

	// 调用加密、解密方法
	public static void main(String args[]) throws Exception {
		String a = DESUtils.encode("TYT124");//加密字符串
		System.out.println(a);
		System.out.println(DESUtils.decode(a));//解密字符串
	}
}
